﻿using System.Text;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	public class VCardResult : ActionResult
	{
		private readonly VCard _vCard;

		public VCardResult(VCard vCard)
		{
			_vCard = vCard;
		}

		protected VCardResult()
		{
		}

		public override void ExecuteResult(ControllerContext context)
		{
			var response = context.HttpContext.Response;
			response.ContentType = "text/vcard";
			response.AddHeader("Content-Disposition", "attachment; fileName=" + _vCard.FirstName + " " + _vCard.LastName + ".vcf");

			var cardString = _vCard.ToString();
			var inputEncoding = Encoding.Default;
			var outputEncoding = Encoding.GetEncoding("windows-1257");
			var cardBytes = inputEncoding.GetBytes(cardString);

			var outputBytes = Encoding.Convert(inputEncoding, outputEncoding, cardBytes);

			response.OutputStream.Write(outputBytes, 0, outputBytes.Length);
		}
	}
}